package example.springboot.controller;

import example.springboot.common.Result;
import example.springboot.dto.PageResult;
import example.springboot.dto.StudyRecordDTO;
import example.springboot.entity.StudyRecord;
import example.springboot.service.StudyRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 *
 * @Author 董熠涛
 * @Date 2025/6/16 20:22
 */
@RestController
@RequestMapping("/api/admin/study-records")
@CrossOrigin
public class StudyRecordController {

    @Autowired
    private StudyRecordService studyRecordService;

    /**
     * 获取学习记录列表（分页）
     */
    @GetMapping
    public Result<PageResult<StudyRecordDTO>> getStudyRecords(
            @RequestParam(required = false) Integer userId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        try {
            PageResult<StudyRecordDTO> result = studyRecordService.getStudyRecordList(userId, startDate, endDate, page, size);
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取学习记录失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取学习记录详情
     */
    @GetMapping("/{id}")
    public Result<StudyRecord> getStudyRecordById(@PathVariable Integer id) {
        try {
            StudyRecord record = studyRecordService.findById(id);
            if (record == null) {
                return Result.error("学习记录不存在");
            }
            return Result.success(record);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取学习记录失败：" + e.getMessage());
        }
    }

    /**
     * 创建学习记录
     */
    @PostMapping
    public Result<StudyRecord> createStudyRecord(@RequestBody StudyRecord record) {
        try {
            StudyRecord createdRecord = studyRecordService.createStudyRecord(record);
            return Result.success("创建成功", createdRecord);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建学习记录失败：" + e.getMessage());
        }
    }

    /**
     * 删除学习记录
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteStudyRecord(@PathVariable Integer id) {
        try {
            boolean success = studyRecordService.deleteStudyRecord(id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除学习记录失败：" + e.getMessage());
        }
    }
}

